package com.demo.lottery.quantity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;


/**
 * @author wangfengchen
 * 抽奖类
 */
public class Lottery {
  // 奖品列表
  private List<Prize> prizes;
  // 奖品总次数
  private int totalQuantity;

  public Lottery(List<Prize> prizes) {
    this.prizes = new ArrayList<>(prizes);
    calculateTotalQuantity();
    calculateCumulativeQuantities();
  }

  /**
   * 计算奖品总次数
   */
  private void calculateTotalQuantity() {
    totalQuantity = 0;
    for (Prize prize : prizes) {
      totalQuantity += prize.getQuantity();
    }
  }

  /**
   * 计算每个奖品的累计次数
   */
  private void calculateCumulativeQuantities() {
    int cumulativeQuantity = 0;
    for (Prize prize : prizes) {
      cumulativeQuantity += prize.getQuantity();
      prize.setCumulativeQuantity(cumulativeQuantity);
    }
  }

  /**
   * 抽奖
   *
   * @return
   */
  public Prize draw() {
    Random random = new Random();
    // 生成随机数
    int randomNumber = random.nextInt(totalQuantity) + 1;
    for (Prize prize : prizes) {
      // 如果随机数小于等于奖品的累计次数，则返回该奖品
      if (randomNumber <= prize.getCumulativeQuantity()) {
        return prize;
      }
    }
    return prizes.get(prizes.size() - 1);
  }


  public static void main(String[] args) {
    List<Prize> prizes = Arrays.asList(
        new Prize("一等奖", 10),
        new Prize("二等奖", 10),
        new Prize("三等奖", 20),
        new Prize("谢谢参与", 60)
    );

    int[] result = new int[prizes.size()];
    Lottery lottery = new Lottery(prizes);
    for (int i = 0; i < 10000; i++) {
      Prize prize = lottery.draw();
      result[prizes.indexOf(prize)]++;
    }
    System.out.println("一等奖：" + result[0]);
    System.out.println("二等奖：" + result[1]);
    System.out.println("三等奖：" + result[2]);
    System.out.println("谢谢参与：" + result[3]);
  }


}